$(document).ready(function(){
	getCategoryChildMaintain();
});

function getCategoryChildMaintain(){
	$('#table_list').DataTable({
        dom: '<"top">rt<"bottom"flip><"clear">',
        language: {
            "sUrl":'../static/plugins/datatables/language.json'
        },
        "searching": false,
        "processing": true,
        "serverSide": true,
        ajax:{
            url:'/category-child-maintain/get-category-child-maintain',
            type:'post',
            data:function(d){
            	d.category_id = $('#category_id').val();
            },
            error:getError
        },
        aoColumns: [
            { "data": "", "bSortable": false},
            { "data": "sort", "bSortable": false },
            { "data": "category_name", "bSortable": false },
            { "data": "category_child_name", "bSortable":false },
            { "data": "banner_config", "bSortable":false },
            { "data": "banner_config", "bSortable":false },
            { "data": "platform", "bSortable":false },
            { "data": "use_flg", "bSortable":false }
        ],
        columnDefs: [
            {
                "targets": [0],
                "orderable":false,
                "searchable":false,
                "render": function(data, type, full) {
                	return '<a href="javascript:" onclick="categoryChildMaintain('+ full.id +',1)">修改</a>	&nbsp;|&nbsp;<a href="javascript:" onclick="categoryChildMaintain('+ full.id +',2)">查看</a>';
                }
            },
            {
                "targets": [1],
                "orderable":false,
                "searchable":false,
                "render": function(data, type, full) {
                	return full.category_name == '奢品' ? '--' : '<input type="text" '+(data == 1 ? 'checked="checked"' : '')+' value="'+data+'" class="form-control"><a href="javascript:" onclick="changeCategoryChildMaintainSort('+ full.id +',this)">&nbsp;&nbsp;修改</a>';
                }
            },
            {
                "targets": [2],
                "orderable":false,
                "searchable":false,
                "render": function(data, type, full) {
                	return data ? data : '--';
                }
            },
            {
                "targets": [3],
                "orderable":false,
                "searchable":false,
                "render": function(data, type, full) {
                	return data ? data : '--';
                }
            },
            {
                "targets": [4],
                "orderable":false,
                "searchable":false,
                "render": function(data, type, full) {
                	var picture_url = '';
                	if(full.banner_config != '' && full.banner_config != null){
                		picture_url = data[0].picture_url;
                	}
                	return full.category_name == '奢品' ? '--' : '<a href="javascript:;" onclick="showMoreImg(\''+picture_url+'\')">查看图片</a>';
                }
            },
            {
                "targets": [5],
                "orderable":false,
                "searchable":false,
                "render": function(data, type, full) {
                	var content = '';
                	if(full.banner_config != '' && full.banner_config != null){
                		content = data[0].ext2;
                	}
                	return full.category_name == '奢品' ? '--' : '<input value="'+content+'" type="hidden"/><a href="javascript:;" onclick="showMoreContent(this)">查看内容</a>';
                }
            },
            {
                "targets": [6],
                "orderable":false,
                "searchable":false,
                "render": function(data, type, full) {
                	return data == 1 ? 'pc' : 'wap';
                }
            },
            {
                "targets": [7],
                "orderable":false,
                "searchable":false,
                "render": function(data, type, full) {
                	return '<span class="switch" data-id="'+ full.id +'" data-flg="'+(data == 1 ? 0 : 1)+'"><input  style="width:20px;height:20px;" type="checkbox" '+(data == 1 ? 'checked="checked"' : '')+' class="input-check"></span>';
                }
            }
        ]
    });
}

function table_list_reload(){
	var table = $('#table_list').DataTable();
    table.ajax.reload();
}

function categoryChildMaintain(id,type){
	$.post('/category-child-maintain/category-child-maintain-detail',{id:id},success,'json');
	return false;
    function success(data){
        $.jBox.close();
        if(data.code == 200)
        {
        	$('#category-child-maintain-modal').modal('show');
        	var result = data.val;
        	if(type == 1){
            	$('#category_id_tow').val(result.category_id);
            	var where = $('#category_id_tow');
            	changeCategory(where,result.category_child);
            	var banner = result.banner_config;
            	if(result.category_name == '奢品'){
            		var html = '';
            		if(banner.length > 0){
            			banner.forEach(function(data,index){
            				html += '<tr>';
            				html += '<td><input name="product_url[]" value="'+data.product_url+'" class="form-control"><input name="banner_config_id[]" value="'+data.id+'" type="hidden"></td>';
            				html += '<td><button type="button" class="btn btn-success depart-modal upload-img-btn" style="width: 100px;" data-type="2">上传</button><input type="hidden" value="'+data.picture_url+'" name="picture_url[]" class="form-control"></td>';
            				if(data.picture_url){
            					html += '<td><button onclick="showImg(\''+data.picture_url+'\')" type="button" class="btn btn-success depart-modal show-img-btn">查看图片</button></td>';
            				}else{
            					html += '<td></td>';
            				}
            				html += '<td><a href="javascript:;" class="up_input_table_tr">上移</a> <a href="javascript:;" class="down_input_table_tr">下移</a> <a class="del_input_table_tr" href="javascript:;">删除</a></td>';
            				html += '</tr>';
            			});
            			$('#input_table').find('tbody').html(html);
            		}
            	}else{
            		$('#sort').val(result.sort);
            		var imageBathUrl = $('#imageBathUrl').val();
            		if(banner.length > 0){
            			if(banner[0].picture_url){
            				var img_url = imageBathUrl+banner[0].picture_url;
                    		$('#category-child-maintain-modal').find('.bgimg').attr('src',img_url);
                    		$('#category-child-maintain-modal').find('.picture_class').children('input').val(banner[0].picture_url);
            			}
            		}
            		if(banner.length > 0){
            			$('#product_url').val(banner[0].product_url);
                		$('#ext2').val(banner[0].ext2);
            		}
            	}
            	$('#platform').val(result.platform);
            	$('#use_flg').val(result.use_flg);
            	$('#hot_sale_id').val(result.id);
        	}else{
        		var id = $('#category-child-maintain-modal');
        		id.find('.platform').addClass('hide');
        		id.find('.child_father').addClass('hide');
        		id.find('.child_project').addClass('hide');
        		id.find('.select_html').removeClass('hide');
        		id.find('.select_html_2').removeClass('hide');
        		id.find('.platform_2').removeClass('hide');
        		$('.select_html').find('.category_father').html('<label for="tag_group_id_add">所属一级分类</label>：'+result.category_name);
        		var banner = result.banner_config;
        		var class_html = $('.select_html_2');
        		if(result.category_name == '奢品'){
        			class_html.find('.category_child').removeClass('hide');
        			class_html.find('.sort').addClass('hide');
        			class_html.find('.picture_class').addClass('hide');
        			class_html.find('.picture_table').removeClass('hide');
        			class_html.find('.product_url').addClass('hide');
        			class_html.find('.ext2').addClass('hide');
        			class_html.find('.category_child').html('<label for="tag_group_id_add">所属二级分类</label>：'+result.category_child_name);
        			var html = '<table class="table table-hover" id="input_table"><thead><tr><th width="40%">图片链接</th><th width="20%">查看图片</th></tr></thead><tbody class="tbody-class">';
    				if(banner.length > 0){
            			banner.forEach(function(data,index){
            				html += '<tr>';
            				html += '<td>'+data.product_url+'</td>';
            				if(data.picture_url){
            					html += '<td><button onclick="showImg(\''+data.picture_url+'\')" type="button" class="btn btn-success depart-modal show-img-btn">查看图片</button></td>';
            				}else{
            					html += '<td></td>';
            				}
            				html += '</tr>';
            			});
            		}
                    html += '</tbody></table>';
                    class_html.find('.picture_table').html(html);
        		}else{
        			class_html.find('.category_child').addClass('hide');
        			class_html.find('.sort').removeClass('hide');
        			class_html.find('.picture_class').removeClass('hide');
        			class_html.find('.picture_table').addClass('hide');
        			class_html.find('.product_url').removeClass('hide');
        			class_html.find('.ext2').removeClass('hide');
        			class_html.find('.sort').html('<label for="tag_group_id_add">排序：</label>'+result.sort);
        			class_html.find('.picture_class').children('img').attr('src',result.picture_url);
        			class_html.find('.product_url').html('<label for="tag_group_id_add">点击链接：</label>'+banner[0].product_url);
        			class_html.find('.ext2').html('<label for="tag_group_id_add">内容：</label>'+banner[0].ext2);
        		}
        		class_html.find('.use_flg').html('<label for="tag_group_id_add">状态：</label>'+(result.use_flg == 1 ? '启用' : '禁用'));
        		$('.platform_2').html('<label for="tag_group_id_add">平台：</label>'+(result.platform == 1 ? 'pc' : 'wap'));
        	}
        }
        else{
            $.jBox.error(data.val, '错误');
        }
    }
}

function changeCategoryChildMaintainSort(id,where){
	var sort = $(where).prev().val();
	$.post('/category-child-maintain/change-category-child-maintain-sort',{id:id,sort:sort},success,'json');
    return false;
    function success(data){
        $.jBox.close();
        if(data.code == 200)
        {
            $.jBox.tip('处理成功', 'success');
            window.setTimeout(function () { table_list_reload(); }, 1000);
        }
        else{
            $.jBox.error(data.val, '错误');
        }
    }
}

function changeCategoryChildMaintainStatus(id,use_flg){
	title = '确定停用此维护的二级分类？';
	if(use_flg == 1){
		title = '确定启用此维护的二级分类？';
	}
	$.jBox.confirm(title, "提示", function(v){
        if (v == 'ok'){
            $.post('/category-child-maintain/change-category-child-maintain-status',{id:id,use_flg:use_flg},success,'json');
            return false;
            function success(data){
                $.jBox.close();
                if(data.code == 200)
                {
                    $.jBox.tip('处理成功', 'success');
                    window.setTimeout(function () { table_list_reload(); }, 1000);
                }
                else{
                    $.jBox.error(data.val, '错误');
                }
            }
        }else{
            $.jBox.close();
            if(use_flg == 1){
        		$('#table_list').find('span[data-id='+id+']').children('input').prop('checked',false);
        	}else{
        		$('#table_list').find('span[data-id='+id+']').children('input').prop('checked',true);
        	}
        }
    });
}

function showMoreImg(objKey){
    if(objKey == '' || objKey == null || objKey == undefined){
        $.jBox.error('数据为空', '错误');
        return;
    }
    var imageBathUrl = $('#imageBathUrl').val();
    var json = {
        "title": "分类图片", //相册标题
        "id": 0, //相册id
        "start": 0, //初始显示的图片序号，默认0
        "data": [   //相册包含的图片，数组格式
            {
                "alt": "",//图片名
                "pid": 0, //图片id
                "src": imageBathUrl + objKey, //原图地址
                "thumb": "" //缩略图地址
            }
        ]
    };
    layer.photos({
        photos: json
    });
}

function showMoreContent(where){
	$('#picture-content-modal').modal('show');
	var content = $(where).prev().val();
	$('#picture_content').text(content);
}

function changeCategory(where,category_child){
	var category_id = $(where).val();
	var id = $('#category-child-maintain-modal');
	id.find('.child_father ').removeClass('hide');
	id.find('.select_html').addClass('hide');
	id.find('.select_html_2').addClass('hide');
	id.find('.platform_2').addClass('hide');
	id.find('.platform').removeClass('hide');
	if(category_id > 0){
		id.find('.child_project').removeClass('hide');
	}else{
		id.find('.child_project').addClass('hide');
	}
	var category_name = $(where).find('option[value='+category_id+']').text();
	if(category_name == '奢品'){
		id.find('.category_child').removeClass('hide');
		id.find('.sort').addClass('hide');
		id.find('.picture_class').addClass('hide');
		id.find('.picture_table').removeClass('hide');
		id.find('.product_url').addClass('hide');
		id.find('.ext2').addClass('hide');
	}else{
		id.find('.category_child').addClass('hide');
		id.find('.sort').removeClass('hide');
		id.find('.picture_class').removeClass('hide');
		id.find('.picture_table').addClass('hide');
		id.find('.product_url').removeClass('hide');
		id.find('.ext2').removeClass('hide');
	}
	if(category_id){
		getCategoryChild(category_id,category_child);
	}
}

//重置操作
$('#reset_button').click(function(){
    $('#category_id').val('');
    table_list_reload();
});

$('table').on('click','.input-check',function(){
	var id = $(this).parent().attr('data-id');
	var use_flg = $(this).parent().attr('data-flg');
	changeCategoryChildMaintainStatus(id,use_flg);
});

function getCategoryChild(category_id,category_child){
	$.post('/category-child-maintain/get-category-child',{category_id:category_id},success,'json');
	return false;
    function success(data){
        $.jBox.close();
        if(data.code == 200)
        {
        	var html = '<option value="0">-请选择-</option>';
            var result = data.val;
            if(result.length > 0){
            	result.forEach(function(data,index){
            		html += '<option value="'+data.id+'" '+(category_child == data.id ? 'selected' : '')+'>'+data.category_name+'</option>';
            	});
            }
            $('#category_child').html(html);
        }
        else{
            $.jBox.error(data.val, '错误');
        }
    }
}

$('#add_input').click(function(){
    var html = '<tr>'+
    	'<td><input name="product_url[]" class="form-control"><input name="banner_config_id[]" value="0" type="hidden"></td>'+
        '<td><button type="button" class="btn btn-success depart-modal upload-img-btn" style="width: 100px;" data-type="2">上传</button><input type="hidden" name="picture_url[]" class="form-control"></td>'+
        '<td></td>'+
        '<td><a href="javascript:;" class="up_input_table_tr">上移</a> <a href="javascript:;" class="down_input_table_tr">下移</a> <a class="del_input_table_tr" href="javascript:;">删除</a></td>'+
        '</tr>';
    $('#input_table').find('tbody').append(html);
});

$('table').delegate('.del_input_table_tr','click',function(){
    $(this).parents('tr').remove();
});

$('table').delegate('.up_input_table_tr','click',function(){
    var tr_index = $(this).parents('tr').index();
    if(eval(tr_index) == 0){
        return true;
    }else{
        var obj = $(this).parents('tr').clone();
        $(this).parents('tr').prev().before(obj);
        $(this).parents('tr').remove();
    }
});

$('table').delegate('.down_input_table_tr','click',function(){
    var tr_index = $(this).parents('tr').next().index();
    if(eval(tr_index) > eval(-1)){
        var obj = $(this).parents('tr').clone();
        $(this).parents('tr').next().after(obj);
        $(this).parents('tr').remove();
    }
});

$('#category_child_maintain_form').delegate('.upload-img-btn','click',function(){
	var len = $(this).parents('tr').index();
	$('#check_img_val').val(len);
	$('#img_type').val($(this).attr('data-type'));
    $('.upload_file_ot').trigger('click');
});

$('.upload_file_ot').change(function(){
    if(this.value != ''){
    	$('#upload_form_update').submit();
    }
});

$('#upload_form_update').submit(function(e){
    e.preventDefault();
    $(this).ajaxSubmit({
        success:function(data){
            var result = $.parseJSON(data);
            if(result.code == 500){
                $.jBox.error(result.val, '错误');
            }else{
            	var type = $('#img_type').val();
            	var imageBathUrl = $('#imageBathUrl').val();
            	if(type == 1){
            		var img_url = imageBathUrl+result.val;
            		$('#category-child-maintain-modal').find('.bgimg').attr('src',img_url);
            		$('#category-child-maintain-modal').find('.bgimg').next().val(result.val);
            	}else{
            		var len = $('#check_img_val').val();
                    var i=0;
            		$('.tbody-class').find('tr').each(function(){
                		if(eval(len) == eval(i)){
                			$(this).find('input[name="picture_url[]"]').val(result.val);
                			var viewpic = '<button onclick="showImg(\''+result.val+'\')" type="button" class="btn btn-success depart-modal show-img-btn">查看图片</button>';
                			$(this).find('.upload-img-btn').parent().next('td').html(viewpic);
                		}
                    	i++;
                    });
            	}
            	$('input[type=file]').closest('form').get(0).reset();
            }
        }
    });
});

function showImg(img_url){
	if(img_url == '' || img_url == null || img_url == undefined){
        $.jBox.error('数据为空', '错误');
        return false;
    }
	var json = {
        "title": "分类图片", //相册标题
        "id": 0, //相册id
        "start": 0, //初始显示的图片序号，默认0
        "data": [   //相册包含的图片，数组格式
            {
                "alt": "",//图片名
                "pid": 0, //图片id
                "src": $('#imageBathUrl').val() + img_url, //原图地址
                "thumb": "" //缩略图地址
            }
        ]
    };
    layer.photos({
        photos: json
    });
}

$('.ajax_post_tag').on('click',function(){
	var form = $('#category_child_maintain_form');
    var category_id = $('#category_id_tow').val();
    if(category_id == '' || category_id == 0){
        $.jBox.error('请选择所属一级分类', '错误');
        return false;
    }
    var category_name = $('#category_id').find('option[value='+category_id+']').text();
    if(category_name == '奢品'){
    	var category_child = $('#category_child').val();
    	if(category_child == '' || category_child == 0){
            $.jBox.error('请选择所属二级分类', '错误');
            return false;
        }
    	var tr_num = $('#input_table').find('tbody').children('tr').length;
    	if(tr_num == 0){
        	$.jBox.error('至少填写一个图片信息', '错误');
            return false;
        }
    }else{
    	var sort = $('#sort').val();
    	if(sort == ''){
            $.jBox.error('请填写二级分类排序编号', '错误');
            return false;
        }
    	var picture_url = $('input[name="picture_url_dan"]').val();
    	if(picture_url == ''){
            $.jBox.error('请上传一张商品图片', '错误');
            return false;
        }
    }
    $.post(form.attr('action'),form.serialize(),success,'json');
    return false;
	function success(data){
        if(data.code == 200)
        {
            $.jBox.tip('处理成功', 'success');
            window.setTimeout(function () {
                $('#category-child-maintain-modal').modal('hide');
                window.setTimeout(function () { table_list_reload(); }, 1000);
            }, 1000);
        }
        else{
            $.jBox.error(data.val, '错误');
        }
	}
});

$('.add-hot-sale').on('click',function(){
	$('#category-child-maintain-modal').modal('show');
	$('#category-child-maintain-modal').find('.child_father').removeClass('hide');
	$('#category-child-maintain-modal').find('.child_project').addClass('hide');
	$('#category-child-maintain-modal').find('.select_html').addClass('hide');
	$('#category-child-maintain-modal').find('.select_html_2').addClass('hide');
	$('#category_id_tow').val(0);
	$('#category_child').val(0);
	$('.upload-img-btn').parent().find('img').attr('src','');
	$('.picture_class').find('input[name=picture_url_dan]').val('');
	$('#input_table').find('tbody').html('');
	$('#product_url').val('');
	$('#ext2').val('');
	$('#use_flg').val(1);
	$('#hot_sale_id').val('');
});